﻿/************************************ AAAMenu object ********************************************/

AAAMenu = function(mapDiv, AAAMap)
{
    var styleTag = document.createElement("style");
    styleTag.setAttribute("type","text/css");
   
    var stringa = "ul#menuDX,ul#vehicle {background:#def17e; width:150px; clear:both; list-style-type:none; margin:0; padding:0;} "+
    "ul#menuDX li ,ul#vehicle li {   border-width:5px; border-style:none solid; border-color:#bbeb00; display:block; padding:0 1em; min-height:1.5em; !important; height:1.5em;" + 
    "line-height:1.5em; text-decoration:none;color:#187418;} ul#menuDX li:hover,ul#vehicle li:hover{ cursor : pointer; border-color:#187418; background:#97cb01;}";
    
    if(navigator.appName=="Microsoft Internet Explorer")
        styleTag.styleSheet.cssText = stringa;
    else
        styleTag.appendChild(document.createTextNode(stringa));    
    
    document.getElementsByTagName("head")[0].appendChild(styleTag);
    mapDiv._visibleMenu = null;
    mapDiv._visibleMenuType = -1;
    mapDiv._currentMenuItem = null;
    mapDiv._onMenuItem = false;
    this._mapDiv = mapDiv;
    this._currentMenuId = null;
    
    // private fields
    this._map= AAAMap;
    this._pointClick;
    this.passengerManagingEnabled = false;
    this._theOnlyMarker = null;   
    this._theOnlyListener = null;
    this._showed = false;
    
    // menu parameters
    this._markerClicked = null;
    this._markerClickedIndex = -1;
    this._routeSelected = null;
    this._subrouteIndex = -1;
    this._routeSelectedIndex = -1;
    
    // polyline context menu definition
    this.polymenuDiv = this._createMenuDiv('polymenuDiv');
    this.polymenuDiv.click = false;
    this.polymenuDiv.style.width="170px";
    this.polymenuDiv.vehicleShowed=false;
    this.polymenuDiv._menu = this;
    mapDiv.appendChild(this.polymenuDiv);
    this.polylistDiv = document.createElement("ul");
    this.polylistDiv.id=("menuDX");
    this.polylistDiv.style.width="170px";
    this.polymenuDiv.appendChild(this.polylistDiv);
    
    // vehicle context menu definition
    this.vehiclemenuDiv = this._createMenuDiv('vehiclemenuDiv', this.polymenuDiv);
    this.listVehicleDiv = document.createElement("ul");
    this.listVehicleDiv.id= "vehicle";
    this.listVehicleDiv.style.width = "170px";
    this.vehiclemenuDiv.appendChild(this.listVehicleDiv);
    mapDiv.appendChild(this.vehiclemenuDiv);
    
    //map context menu definition
    this.mapmenuDiv = this._createMenuDiv('mapmenuDiv');
    this.mapmenuDiv.style.width="170px"; 
    mapDiv.appendChild(this.mapmenuDiv);
    this.maplistDiv = document.createElement("ul");
    this.maplistDiv.id=("menuDX");
    this.mapmenuDiv.appendChild(this.maplistDiv);      
    
    // marker context menu definition
    this.markermenuDiv = this._createMenuDiv('markermenuDiv');
    this.markermenuDiv.click = false;
    this.markermenuDiv.style.width="170px"; 
    mapDiv.appendChild(this.markermenuDiv);
    this.markerlistDiv = document.createElement("ul");
    this.markerlistDiv.id=("menuDX");
    this.markerlistDiv.style.width="170px";
    this.markermenuDiv.appendChild(this.markerlistDiv);    
    
    // passenger managing
    this._takeInMenu = this._createMenuItem('take_in',mapStrings["take_in_passenger"], 
        GEvent.callback(this, this._takeIn), true);
    this._takeOffMenu = this._createMenuItem('take_in',  mapStrings["take_off_passenger"], 
        GEvent.callback(this, this._takeOff), true);
    this._detachPassMenu = this._createMenuItem('detach_p',mapStrings["detach_passenger"], 
        GEvent.callback(this, this._detachPassenger), true);
    this._detachFromTripMenu = this._createMenuItem('detach_from_trip', mapStrings["detach_from_trip"],
        GEvent.callback(this, this._detachPassenger), true);
    
    // some useful arrays and functions
    this.menuDivs = new Array(this.mapmenuDiv, this.polymenuDiv, this.markermenuDiv, this.vehiclemenuDiv);
    this.preprocessors = new Array(this._mapmenuPreprocessing, this._polymenuPreprocessing, 
        this._markermenuPreprocessing, null);
    this.menuLists = new Array(this.maplistDiv, this.polylistDiv, this.markerlistDiv, this.listVehicleDiv);
    this._hideMenu = Function.createDelegate(this, this.hideMenu);
    var me = this;
    
    // map click --> menu hide
    GEvent.addListener(AAAMap, 'click', function(o, ll){me._hideMenu()});
    
    var menu = new Array();
    /************** Polyline context menu items *********************/    
    menu[0] = this._createMenuItem('insert_point', mapStrings["insert_waypoint"], GEvent.callback(this, this._addPoint), true); 
    this.polylistDiv.appendChild(menu[0]);
    
    var vehicleMenuForClosures = this.vehiclemenuDiv;
    menu[1] = this._createMenuItem('selectVehicle', mapStrings["select_vehicle"], 
        function()
        {
            if (!vehicleMenuForClosures.hidden)
                vehicleMenuForClosures.hide(false);
            else
                vehicleMenuForClosures.show();
        }, false);
    menu[1].style.height = "1.5em";
    this.polylistDiv.appendChild(menu[1]);
    this.vehiclemenuDiv._show = this.vehiclemenuDiv.show;
    
    var polyMenuForClosures = this.polymenuDiv;
    this.vehiclemenuDiv.show = function(){
        var leftString = polyMenuForClosures.style.left;
        var topString = polyMenuForClosures.style.top;
        var topInt = parseInt(topString.substring(0, topString.length - 2));
        var leftInt = parseInt(leftString.substring(0, leftString.length - 2));
        var left = leftInt + menu[1].clientWidth + 10;
        var top = topInt + menu[1].offsetTop;
        vehicleMenuForClosures._show(left + 'px', top + 'px');
        if (MapControl2.NAVIGATOR_IS_IE){ // bugfix on IE
            polyMenuForClosures.style.top = (topInt + 5) + 'px';
            vehicleMenuForClosures.style.top = (topInt + 5 + menu[1].offsetTop) + 'px';
        }
        mapDiv._visibleMenu = vehicleMenuForClosures;
        mapDiv._visibleMenuType = 3;
    };
    /************** End Polyline context menu *********************/   
 
    /************** Map context menu *********************/   
    this._addDestinationMenu = this._createMenuItem('add_d',mapStrings["add_destination"], 
        GEvent.callback(this, this._addDestination), true);
    this._removeTripMenu = this._createMenuItem('rem_t',mapStrings["remove_trip"], 
        function(){AAAMap.clearEditableTrip();}, true); 
    this.maplistDiv.appendChild(this._addDestinationMenu);
    this.maplistDiv.appendChild(this._removeTripMenu);
    /************** End Map context menu *********************/   
};

AAAMenu.prototype = {
    
    // ------------------ private functions ----------------------------------------------------------
    _setVehicleMenu: function(listVehicle)
    {
        var menu = null;
        for(var i = 0; i< listVehicle.length; i++)
        {
            menu = this._createMenuItem('vehicle ' + i, listVehicle[i].Type, function(){}, true);
            menu.associatedVehicle = listVehicle[i];
            menu.onclick = Function.createDelegate(menu, this._vehicleMenuHandler);
            $get("vehicle").appendChild(menu);
        }
    },
    
    _createMenuItem: function(id, text, clickHandler, closeOnClick){
        var item = document.createElement('li'), me = this;
        item.id = id;
        item.appendChild(document.createTextNode(text));
        item.style.borderBottom = "2px ridge #187418";
        item._map = this._map;
        item.onclick = function(e){
                if(closeOnClick)me._hideMenu(true);
                clickHandler();
            };
        item.onmouseover = function(e){
                me._mapDiv._currentMenuItem = item;
                me._mapDiv._onMenuItem = true;
            };
        return item;
    },
    
    _createMenuDiv: function(id, parentMenu){
        var menuDiv = document.createElement('div');
        menuDiv.style.backgroundColor = "#def17e";
        menuDiv.style.height="0";
        menuDiv.style.width="150px";
        menuDiv.style.position = "relative";
        menuDiv.style.top = "-10020px";
        menuDiv.style.left = "-10020px";
        menuDiv.id = id;
        if (parentMenu)
            menuDiv.parentMenu = parentMenu;
        else
            menuDiv.parentMenu = null;
        menuDiv.style.fontFamily = "Verdana, Arial, Helvetica, sans-serif";
        menuDiv.style.fontSize = "10pt";
        menuDiv.style.zIndex = "0";
        menuDiv.hidden = true;
        menuDiv.hide = function(hideparent)
            {   
                menuDiv.style.top = "-10020px";
                menuDiv.style.left = "-10020px";
                menuDiv.hidden = true;
                if (menuDiv.parentMenu != null && hideparent)
                    menuDiv.parentMenu.hide(true);
            };
        menuDiv.show = function(x, y){
                menuDiv.style.top = y;
                menuDiv.style.left = x;
                menuDiv.hidden = false;
            };
        return menuDiv;
    },
    
    // ------------------ preprocessors ------------------------------------------------------------
    _markermenuPreprocessing: function(){ // this._menuArgs[0] --> clicked marker
        if (!this.passengerManagingEnabled) return true;
        var dep = this._map._passengerDep;  
        var arr = this._map._passengerArr;
        var markerClicked = this._markerClicked;
        
        // removes old menu elements
        try{this.markerlistDiv.removeChild(this._takeInMenu);}catch(e){}
        try{this.markerlistDiv.removeChild(this._takeOffMenu);}catch(e){}
        try{this.markerlistDiv.removeChild(this._detachPassMenu);}catch(e){}
        try{this.markerlistDiv.removeChild(this._detachFromTripMenu);}catch(e){}
        
        if (markerClicked._attached){
            this.markerlistDiv.appendChild(this._detachFromTripMenu);
        }else{
            if (!dep._attached && dep.isInRadius(this._markerClicked.getLatLng()))
                this.markerlistDiv.appendChild(this._takeInMenu);
            if (!arr._attached && arr.isInRadius(this._markerClicked.getLatLng()))
                this.markerlistDiv.appendChild(this._takeOffMenu);
            if (markerClicked._tookIn || markerClicked._tookOff)
                this.markerlistDiv.appendChild(this._detachPassMenu);
            }
        return (this.markerlistDiv.hasChildNodes());
    },
    
    _polymenuPreprocessing: function(){
        if (!this.passengerManagingEnabled) return true;
        
        try{this.polylistDiv.removeChild(this._takeInMenu);}catch(e){}
        try{this.polylistDiv.removeChild(this._takeOffMenu);}catch(e){}
        
        var dep = this._map._passengerDep;
        var arr = this._map._passengerArr;
        if (!dep._attached)
            this.polylistDiv.appendChild(this._takeInMenu);
        if (!arr._attached)
            this.polylistDiv.appendChild(this._takeOffMenu);
        
        return (this.polylistDiv.hasChildNodes());
    },
    
    _mapmenuPreprocessing: function(){
        try{this.maplistDiv.removeChild(this._removeTripMenu);}catch(e){}
        if (this._map.getEditableTrip() != null && !this.passengerManagingEnabled)
            this.maplistDiv.appendChild(this._removeTripMenu);
        
        return (this.maplistDiv.hasChildNodes());
    },
    // ---------------------------------------------------------------------------------------------
    // ---------------------------------------------------------------------------------------------
    
    // --------------------- event handlers --------------------------------------------------------
    _vehicleMenuHandler: function(aaaMenu) {
        var aaaMenu = this._map._menu;
        var editableTrip = aaaMenu._map.getEditableTrip();
        editableTrip.setVehicle(this.associatedVehicle);
        var vehicleCbo = aaaMenu._map._myCtrl._stuff.vehicleCbo;
        if (vehicleCbo != null){
            if (vehicleCbo.value != this.associatedVehicle.Id){
                vehicleCbo.value = this.associatedVehicle.Id;
                var cboName = aaaMenu._map._myCtrl._stuff.cboName;
                //raises the onchange event on combo box
                setTimeout('__doPostBack("' + cboName + '","")', 0); 
            }
        }
        aaaMenu.hideMenu();
    },
    
    _addDestination: function(){
        if (this._map._editableTrip != null)
            this._map._editableTrip.addDestination(this._pointClick);
        else
            if (this._theOnlyMarker == null){
                var depBox = this._map._myCtrl._stuff.depBox;
                this._theOnlyMarker = this._map.addExplorator
                    (this._pointClick, MapControl2.AAAMarker.START_MARKER);
                this._theOnlyListener = GEvent.addListener(this._theOnlyMarker, 'exploration_performed', 
                        function(expl){
                            if (depBox != null)
                                depBox.value = expl.getGeoLoc().address;});
            }else{
                this._map.removeExplorator(this._theOnlyMarker);
                var loadListener = GEvent.addListener(this._map, 'tripload', 
                    function(trip)
                    {trip._markers[1].checkPosition(function(){GEvent.trigger(trip._parentMap, 'tripchange', trip);});
                     GEvent.removeListener(loadListener)});
                var vehicleCbo = this._map._myCtrl._stuff.vehicleCbo, myVehicle = null;
                if (vehicleCbo == null){
                    myVehicle = this._map._listVehicles[0];
                }else{
                    myVehicle = this._map._myCtrl.getVehicleById(vehicleCbo.value);
                }
                var mouseLatLng = this._pointClick;
                var depBox = this._map._myCtrl._stuff.depBox, arrBox = this._map._myCtrl._stuff.arrBox;
                if (depBox != null){
                    depBox.latitude = this._theOnlyMarker._geoloc.lat;
                    depBox.longitude = this._theOnlyMarker._geoloc.lng;
                    depBox.SetStatus(3);
                }
                if (arrBox != null){
                    arrBox.latitude = mouseLatLng.lat();
                    arrBox.longitude = mouseLatLng.lng();
                    arrBox.SetStatus(3);
                }
                this._map._myCtrl.setEditableTripA2BFromGeolocs
                    ([this._theOnlyMarker._geoloc, 
                      MapControl2.AAAUtils.createGeoLocFromLatLng(this._pointClick)], myVehicle);
                GEvent.removeListener(this._theOnlyListener);
                this._theOnlyMarker = null;
                this._theOnlyListener = null;
            }
    },
    
    _addPoint: function(){
        var route = this._routeSelected;
        var subrouteIndex = this._subrouteIndex;
        route.insertWaypoint(subrouteIndex, 
            MapControl2.AAAUtils.createGeoLocFromLatLng(this._pointClick));
    },
    
    _takeIn: function(){
        this._takePassenger(Function.createDelegate(this._map, this._map.gettingInPassenger));
    },
    
    _takeOff: function(){
        this._takePassenger(Function.createDelegate(this._map, this._map.gettingOffPassenger));
    },
    
    _takePassenger: function(gettingFunction){
        switch(this._mapDiv._visibleMenuType){
            case 1: // poly menu
                gettingFunction(this._routeSelectedIndex, this._subrouteIndex);
            break;
            case 2:
                gettingFunction(this._markerClickedIndex);
            break;
        }
    },
    
    _detachPassenger: function(){
        var marker = this._markerClicked;
        if (marker._attached)
            marker.detachToTrip();
        else
            if (marker._tookIn)
                this._map._passengerDep.detachToTrip();
            else
                this._map._passengerArr.detachToTrip();
    },
    // ---------------------------------------------------------------------------------------------
    
    // --------------------- public functions ------------------------------------------------------
    enablePassengerMenuVoices: function(){
        try{this.polylistDiv.removeChild($get('selectVehicle'));}catch(e){} // vehicle freezing
        try{this.maplistDiv.removeChild($get('rem_t'))}catch(e){}    // trip freezing 
        this.passengerManagingEnabled = true;
    },
    
    showMenu: function(point, type){
        this._pointClick = this._map.fromDivPixelToLatLng(point);
        if (this._map.isEditable()){
            var me = this, menuToShow = this.menuDivs[type];
            if (me._showed == true && type < this._mapDiv._visibleMenuType) return;
            var preproc = Function.createDelegate(me, me.preprocessors[type]);
            me._hideMenu(true); // hides the menu that is eventually shown
            this._mapDiv._visibleMenu = menuToShow;
            this._mapDiv._visibleMenuType = type;
            if (!preproc()) return;
            if (MapControl2.NAVIGATOR_IS_IE){ point.y -= 7}
            menuToShow.show(point.x + 'px', point.y + 'px'); // shows the menu
            me._showed = true;
            var handle = setTimeout(function(){clearTimeout(handle); me._showed=false;}, 200);
        }    
    },
    
    hideMenu: function(){
        if (this._mapDiv._visibleMenu != null){
            this._mapDiv._visibleMenu.hide(true);
            this._mapDiv._visibleMenu = null;
        }
    }
    // ---------------------------------------------------------------------------------------------
};